﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;

namespace IconManager.ObjectModel
{
	public class UmbracoIcon : BaseIcon
	{
		internal static string UmbracoIconDirUrl = "/umbraco/images/umbraco/";

		/// <summary>
		/// Gets the Document Types that use this icon
		/// </summary>
		public List<DocumentType> DocumentTypes
		{
			get
			{
				return DocumentType.GetAllAsList().Where(x => x.IconUrl == this.FileName).ToList();
			}
		}

		/// <summary>
		/// Gets the Media Types that use this icon
		/// </summary>
		public List<MediaType> MediaTypes
		{
			get
			{
				return MediaType.GetAllAsList().Where(x => x.IconUrl == this.FileName).ToList();
			}
		}

		/// <summary>
		/// Gets the Member Types that use this icon
		/// </summary>
		public List<MemberType> MemberTypes
		{
			get
			{
				return MemberType.GetAll.Where(x => x.IconUrl == this.FileName).ToList();
			}
		}

		/// <summary>
		/// InUse is true is this icon is currently associated with any Document Type, Media Type or Member Type
		/// </summary>
		public bool InUse 
		{
			get
			{
				if (this.DocumentTypes.Count > 0)
				{
					return true;
				}

				if (this.MediaTypes.Count > 0)
				{
					return true;
				}

				if (this.MemberTypes.Count > 0)
				{
					return true;
				}

				return false;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="UmbracoIcon"/> class.
		/// </summary>
		/// <param name="fileName">Name of the icon file.</param>
		public UmbracoIcon(string fileName)
		{
			this.FileName = fileName;
			this.Url = UmbracoIcon.UmbracoIconDirUrl + this.FileName;
			this.PhysicalPath = HttpContext.Current.Server.MapPath(this.Url);

			// How can we calculate which collection icon this came from (based on just the fileName) ?
		}

		/// <summary>
		/// Deletes the icon file from the Umbraco icons directory (if it's not currently in use)
		/// </summary>
		/// <returns>true to indicate the file was deleted</returns>
		public bool DeActivate()
		{
			bool deactivated = false;

			if (this.Exists)
			{
				if (!this.InUse)
				{
					this.File.Delete();
					deactivated = true;
				}
			}

			return deactivated;
		}
	}
}